﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using AcctrueWMS.Foundation.Web;
using System.Text.RegularExpressions;

namespace AcctrueWMS.Foundation.WebControls
{
    public class AccFocusedTextBox : AccControl
    {
        public const string In = "in";
        public const string NotIn = "notin";
        public const string NoCheck = "nocheck";

        public AccFocusedTextBox()
        {
            MinLength = 1;
        }
        public override string Render()
        {
            // base.Render();
            StringBuilder sb = new StringBuilder();
            #region 生成控件
            // sb.Append(GenerateDescription());
            sb.Append("<nobr>");
            if (ShowValue)
            {
                sb.Append("<span style=\"width:90%;\">");
            }
            sb.Append("<input type='text' class=\"accFocuse\" ");
            sb.Append(GenerateBasicProperty());
            /*
             * 注:JQuery的Form只收集带有name属性的Input的值,故需要收集值时,可以只给隐藏的Input赋name属性,这样收集到的是隐藏Input的值
             * select事件触发时,需给隐藏的Input赋值
             */
            sb.Append(" value='" + GetControlValue() + "' ");

            string checkType = "", columnName = "", modelName = "", sysOnblur="true";
            string onblur = "AccFocusedBlur" + System.Guid.NewGuid().ToString().Replace("-","");
            //模板里面定义的onblur事件
            string tempOnblur = GetOnblurMethot(sb);

            if (CheckExists == AccFocusedTextBox.In || CheckExists == AccFocusedTextBox.NotIn)
            {
                checkType = CheckExists == AccFocusedTextBox.In ? "true" : "false";
                columnName = this.Name.Split('$').Length > 1 ? this.Name.Split('$')[1] : this.Name;
                modelName = this.Name.Split('$').Length > 1 ? this.Name.Split('$')[0] : HttpContext.Current.Request.QueryString["model"];

                //系统校验数据源中是否存在的onblur事件
                sysOnblur = string.Format("wmsCommon.accFocuseBlur('{0}','{1}','{2}',obj)",
                    modelName, columnName, checkType);

                if (!string.IsNullOrEmpty(this.ValidExpression))
                {
                    sb.AppendFormat(@" validpattern='{0}'  tip='{1}' ", this.ValidExpression, Tip); //加验证信息
                    
                }

                sb.AppendFormat(" onblur={0}({1}) ", onblur, "this");
                if (Context.RenderMode == 2)
                {
                    sb.AppendFormat(" ovalue=\"{0}\" ", base.SelectedValue.ToString());
                }
            }
            else
            {
                //sb.AppendFormat(" validpattern='{0}' ", this.ValidExpression);

                if (!string.IsNullOrEmpty(this.ValidExpression))
                {
                    string temp = "wmsCommon.dataValideByRegular(this)";
                    sb.AppendFormat(@" validpattern='{0}' onblur='{1}' tip='{2}' ", this.ValidExpression, temp, Tip);
                }
                else
                {
                    sb.AppendFormat(" onblur={0}({1}) ", onblur, "this");
                }
            }
            sb.Append(" >");
            sb.Append("</input>");

            if (ShowValue)
                sb.Append("</span>");
            // sb.Append("<input id='" + this.Name + "_selectedValue' style='display:none'  value='" + GetControlValue() + "'/>");//暂时去掉

            if (ShowValue)
                sb.AppendFormat("<span style='width:90%;'><input type='text' disabled class=\"AccFocuseSub\" id=\"lbl_{0}\" value=\"{1}\"></input></span>", this.Name, this.Text);//值显示
            if (this.Musted)
            {
                sb.Append("<font style='color:red'>*</font>");
            }
            sb.Append("</nobr>");
            #endregion

            #region 生成脚本
            sb.Append(GenerateScript());

            //onblur事件
            //正则表达式验证onblur事件
            string validExpression = "true";
            if (!string.IsNullOrEmpty(this.ValidExpression))
            {
                validExpression = "wmsCommon.dataValideByRegular(obj)";
            }

            sb.AppendLine("<script language='javascript' type='text/javascript'>");
            sb.AppendLine("function " + onblur + "(obj){");
            sb.AppendLine("//");
            sb.AppendLine("if(!" + sysOnblur + "){");
            sb.AppendLine("    return;");
            sb.AppendLine("}else if(!" + validExpression + "){");
            sb.AppendLine("    return;");
            sb.AppendLine("}");
            sb.AppendLine(tempOnblur.Replace("this","obj"));
            sb.AppendLine("}");
            sb.AppendLine("</script>");
            #endregion
            return sb.ToString();
        }

        public bool ShowValue
        {
            get;
            set;
        }
        public int MinLength
        {
            get;
            set;
        }
        //是否检测用户输入数值 true：检测
        public string CheckExists
        {
            get;
            set;
        }
        public string DataExpression
        {
            get;
            set;
        }
        private string GenerateScript()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<script language='javascript' type='text/javascript'>");
            sb.AppendLine("$(function () {");
            //sb.AppendLine("$('"+GetJQueryID()+"').bgiframe();");//解决z-index;
            sb.AppendLine(" $('#" + GetJQueryID() + "').autocomplete({");
            sb.AppendLine("  source: function (request, response) {");
            // debuggLineer;
            sb.AppendLine("   $.ajax({");
            sb.AppendLine("    type: 'POST',");
            sb.AppendLine("  url: '" + this.Url + "/AutoComplete',");
            sb.AppendLine("  dataType: 'json',");
            sb.AppendLine("  data:\"{startWith:'\"+request.term+\"',limit:10,dataExpr:\'" + HttpUtility.UrlEncode(this.DataExpression) + "\'}\",");
            sb.AppendLine(" contentType: 'application/json; charset=utf-8',");
            sb.AppendLine(" success: function (data) {");
            sb.AppendLine("  response($.map(data.d, function (item) {");
            sb.AppendLine("     return {");
            sb.AppendLine("     label: item." + base.ValueMember + ",");
            sb.AppendLine("     value: item." + base.KeyMember + "");
            sb.AppendLine("  }");
            sb.AppendLine("  }));");
            sb.AppendLine("  },");
            sb.AppendLine(" error: function (XMLHttpRequest, textStatus, errorThrown) {");
            //sb.AppendLine(" ");
            sb.AppendLine(" wmsCommon.alert(errorThrown);");
            sb.AppendLine("   }");
            sb.AppendLine("            });");
            sb.AppendLine("  },");
            sb.AppendLine("  minLength: " + this.MinLength + ",");
            sb.AppendLine("   select: function (event, ui) {");
            //  sb.AppendLine("    $('#" + this.Name + "_selectedValue').text(ui.item." + base.KeyMember + ");");
            ///目前值存放在Text中
            sb.AppendLine("    $('#" + GetJQueryObject(this.Name) + "')[0].value=ui.item." + base.KeyMember + ";");
            sb.AppendLine(" },");
            sb.AppendLine("    open: function () {");
            sb.AppendLine("     $(this).removeClass('ui-corner-all').addClass('ui-corner-top');");
            sb.AppendLine("  },");
            sb.AppendLine(" close: function () {");
            sb.AppendLine("    $(this).removeClass('ui-corner-top').addClass('ui-corner-all');");
            sb.AppendLine("  }");
            sb.AppendLine(" });");
            sb.AppendLine(" });");
            sb.AppendLine("</script>");
            return sb.ToString();

        }

        //提取onblur事件，避免跟系统onblur事件冲突
        private string GetOnblurMethot(StringBuilder sb)
        {
            string onBlurStr = "";
            string onblur = "";
            Regex reg = new Regex(@"onblur='(?<name>.+?\))'");
            Match m = reg.Match(sb.ToString());
            if (m.Success)
            {
                onBlurStr = m.Value;
                onblur = m.Groups["name"].ToString();
                sb = sb.Replace(onBlurStr, "");
            }
            return onblur;
        }
    }
}

